from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from ..models import *
from django.core.urlresolvers import reverse
from django.contrib.auth.hashers import make_password, check_password
from project_1.settings import BASE_DIR
import json
from .viewsUser import loadFile
from django.http import Http404
from django.contrib.auth.decorators import permission_required

# 列表页
@permission_required("myadmin.show_goods")
def index(request):
	data = Goods.objects.exclude(status=3)
	# 数据分页
	from django.core.paginator import Paginator
	from django.db.models import Q
	# 查询
	res = request.GET.dict()
	if (len(res)>1):
		status = {"热卖":1,"下架":3,"新发布":0,}
		if res['types'] == "all":
			val = res['textVal']
			if res['textVal'] in status:
				data = Goods.objects.filter(Q(status__contains=status[res['textVal']])|Q(title__contains=val)).exclude(status=3)
			else:
				# try:
				# 	ca = Cates.objects.get(name=val)
				# 	zi = Cates.objects.filter(pid=ca.id)
				# 	zname = []
				# 	for i in zi:
				# 		zname.append(i.name)
				# 	data = data.filter(title__contains=zname)
				# except:
					data = Goods.objects.filter(Q(title__contains=val)|Q(cateid=Cates.objects.filter(name=val))).exclude(status=3)
		elif res['types'] == "price":
			try:
				ree = float(res["mon"])
				if res["mon1"] == "":
					data = Goods.objects.filter(price__gte=float(ree)).exclude(status=3)
					print(data)
				else:
					ree1 = float(res["mon1"])
					data = Goods.objects.filter(price__gte=float(ree),price__lte=float(ree1)).exclude(status=3)
			except:
				data = []
		elif res['types'] == 'status':
			if res['textVal'] in status:
				data = Goods.objects.filter(status__contains=status[res['textVal']]).exclude(status=3)
			else:
				data=[]
		else:
			data = Goods.objects.filter(title__contains=res['textVal']).exclude(status=3)
	
	# 给数据id重新排序
	ind = 1
	for i in data:
		i.ind=ind
		ind+=1
	# 实例化分页类
	paginator = Paginator(data,5)

	# 获取当前页码
	try:
		p = int(request.GET.get('p',1))
	except:
		p=1

	# 获取分页数据对象[{id:1},{id:2}]  [{id:3},{id:4}]
	goodslist= paginator.page(p)

	# 分配数据
	context = {'data':goodslist}
	return render(request,'myadmin/goods/index.html',context)

# 商品添加
@permission_required("myadmin.insert_goods")
def add(request):
	try:
		if request.method == "GET":
			cate = Cates.objects.extra(select={"paths":"concat(path,id)"}).order_by("paths").exclude(isDelete=True)
			return render(request,'myadmin/goods/add.html',{"data":cate})
		else:
			req = request.POST.dict()
			req.pop('csrfmiddlewaretoken')
			req['cateid']=Cates.objects.get(id=req.pop('id'))
			req['pic_url'] = loadFile(request.FILES.get('pic_url'))
			goods = Goods(**req)
			goods.save()
			return HttpResponse("<script>alert('添加成功');location.href='"+reverse('myadmin_goods_index')+"'</script>")

	except:
		return HttpResponse("<script>alert('添加失败');location.href='"+reverse('myadmin_goods_index')+"'</script>")

# 商品删除
@permission_required("myadmin.del_goods")
def delete(request,id):
	da1 = request.GET.dict()
	if da1['p'] == "":
		da1['p']=1
	path1 = "?"
	for v,k in da1.items():
		path1 += v+"="+str(k)+"&"
	try:
		da = Goods.objects.get(id=int(id))
		da.status = 3
		da.save()
		return HttpResponse("<script>alert('删除成功');location.href='"+reverse('myadmin_goods_index')+path1[0:-1]+"'</script>")
	except:
		return HttpResponse("<script>alert('删除失败');location.href='"+reverse('myadmin_goods_index')+path1[0:-1]+"'</script>")

# 商品修改
@permission_required("myadmin.update_goods")
def update(request,id):
	try:
		d = Goods.objects.get(id=id)
		if request.method == "GET":
			data = Cates.objects.filter().exclude(isDelete=True)
			return render(request,'myadmin/goods/update.html',{"d":d,"data":data})
		else:
			import os
			da1 = request.GET.dict()
			if da1['p'] == "":
				da1['p']=1
			path1 = "?"
			for v,k in da1.items():
				path1 += v+"="+str(k)+"&"
			res = request.POST.dict()
			d.title = res['title']
			d.price = res['price']
			d.store = res['store']
			d.info = res['info']
			d.cateid = Cates.objects.get(id=int(res['id']))
			if request.FILES.get('pic_url') == None:
				res['pic_url'] = d.pic_url
			else:
				os.remove(BASE_DIR+d.pic_url)
				d.pic_url = loadFile(request.FILES.get('pic_url'))
			d.cateid = Cates.objects.get(id=d.cateid.id)
			d.save()
			return HttpResponse("<script>alert('修改成功');location.href='"+reverse('myadmin_goods_index')+path1[0:-1]+"'</script>")
	except:
		return HttpResponse("<script>alert('修改失败');location.href='"+reverse('myadmin_goods_index')+path1[0:-1]+"'</script>")


